<!-- 「问卷查看」页面 -->
<template>
  <div class="page">
    <!-- 导航栏 -->
    <uni-nav-bar class="nav-bar" fixed="true" statusBar="true" :border="false" leftIcon="left"
      @clickLeft="backBtnClickHandle">
      <div class="nav-bar-center">
        <div class="title ellipsis"> {{ currentQuestionnaire?.title ?? '' }} </div>
        <image class="more-icon" src="@/static/icons/common/more.svg" @click="showBottomPopup" />
      </div>
    </uni-nav-bar>
    <!-- 页面主体 -->
    <div class="container" @click="toggleShareTipDialog(true)">
      <!-- 问卷头部 -->
      <div class="questionnaire-head">
        <!-- 问卷封面 -->
        <div class="head-cover">
          <image class="img" :src="fixQuestionnaireCover(currentQuestionnaire?.coverImg)" mode="aspectFill" />
        </div>
        <!-- 问卷标题 -->
        <div class="head-title ellipsis">{{
          currentQuestionnaire?.title ?? '' }} </div>
        <!-- 问卷描述 -->
        <div class="questionnaire-describe"> {{
          currentQuestionnaire?.desc ?? '' }} </div>
      </div>
      <!-- 问卷内容 -->
      <div class="content">
        <!-- 不同的问题类型的区块 -->
        <div :class="questionList.questionCategory === identityQuestionCategoryName ? 'identity-block' : 'normal-block'"
          v-for="(questionList, questionListIndex) in currentQuestionnaire?.categoryQuestionList" :key="questionList.id">

          <!-- 身份信息问题特有的结构 -->
          <div class="question" v-if="questionList.questionCategory === identityQuestionCategoryName">
            <text class="title">您的身份是？</text>
            <questionnaire-radio-group class="radio-group" v-model="questionList.questionList[0].options"
              disable></questionnaire-radio-group>
          </div>

          <!-- 一般问题特有的结构 -->
          <!-- 问题类别 -->
          <div class="question-type" v-if="isShowQuestionList(questionList)">
            问题类别：{{ questionList.questionCategory }}
          </div>
          <!-- 问题列表 -->
          <div class="question-list" v-if="isShowQuestionList(questionList)">
            <div class="question" v-for="(question, questionIndex) in questionList.questionList" :key="question.id">
              <text class="question-title">Q{{ questionIndex + 1 }}: {{ question.title }}</text>
              <textarea class="question-input" type="text" v-model="question.answer" auto-height
                :placeholder="question?.placeholder || '请输入内容'" disabled />
            </div>
          </div>
        </div>
        <!-- 结束语 -->
        <div class="conclusion">
          {{ currentQuestionnaire?.conclusion ?? '' }}
        </div>
        <!-- 底部固定栏 -->
        <div class="bottom-bar">
          <!-- 左侧按钮 -->
          <div class="left-btn" @click.stop="settingBtnClickHandle">
            <img class="left-btn-icon" src="@/static/icons/common/gear-six.svg" alt="编辑">
            <text class="left-btn-text">设置</text>
          </div>
          <!-- 右侧按钮 -->
          <button class="right-btn" open-type="share" :data-id="currentQuestionnaire?.id"
            :data-title="currentQuestionnaire?.title ?? ''" @click.stop>分享</button>
        </div>
      </div>
    </div>
    <!-- 底部弹窗 -->
    <uni-popup ref="bottomPopup" backgroundColor="#00000000" type="bottom">
      <div class="delete-popup popup">
        <div class="row" :class="item.className" v-for="item in currentPopupList" :key="item.actionType"
          @click="popupClickHandle(item.actionType)">{{ item.text }}</div>
      </div>
    </uni-popup>
  </div>
  <!-- 分享提示对话框 -->
  <uni-popup ref="shareTipDialog" type="dialog">
    <div class="popup-dialog">
      <span class="popup-dialog-title">提示</span>
      <span class="popup-dialog-content">问卷已创建成功，快去分享给新人吧~</span>
      <div class="popup-dialog-cancel-btn" @click="shareTipDialogCancelBtnClickHandle">
        <button class="button">取消</button>
      </div>
      <div class="popup-dialog-confirm-btn" @click="shareTipDialogConfirmBtnClickHandle">
        <button class="button" open-type="share" :data-id="currentQuestionnaire?.id"
          :data-title="currentQuestionnaire?.title">转发</button>
      </div>
    </div>
  </uni-popup>
</template>

<script lang="ts" setup>
import { ref, getCurrentInstance } from 'vue'
import { useQuestionnaire } from '@/stores/questionnaire'
import { navigateTo } from "@/utils/navigate"
import { onLoad, onShareAppMessage, onUnload } from '@dcloudio/uni-app';
import QuestionnaireRadioGroup from '@/components/questionnaire-radio-group.vue'
import { storeToRefs } from 'pinia';
import { editQuestionnairePopupList, identityQuestionCategoryName } from '@/static/constants/questionnaire-constant';
import { reqEditQuestionnaire } from '@/api/api-questionnaire'
import { showToast } from '@/utils/tools';
import { fixQuestionnaireCover, shareQuestionnaire } from '@/utils/others';
import { useUser } from '@/stores/user-store';
import { useQuestionnaireList } from '@/stores/questionnaire-list';

const questionnaire = useQuestionnaire()
const { getAndSetCurrentQuestionnaire } = questionnaire
const { currentQuestionnaire } = storeToRefs(questionnaire)

const questionnaireListStore = useQuestionnaireList()
const { deleteReceivedQuestionnaire } = questionnaireListStore

const userStore = useUser()
const { userInfo } = userStore

/** 当前组件实例 */
const currentInstance = getCurrentInstance()

/** 当前问卷分类 */
const currentQuestionnaireCategory = ref<QuestionnaireCategory>('created')

// 页面挂载后，根据参数设定当前问卷
onLoad((options: any) => {
  currentQuestionnaireCategory.value = options.questionnaireCategory
  getAndSetCurrentQuestionnaire(options.questionnaireId, options.questionnaireCategory)
})

/** 根据questionList判断是否显示该结构 */
const isShowQuestionList = (questionList: CategoryQuestion) => {
  return questionList.questionCategory != identityQuestionCategoryName
    && questionList.questionList.length > 0
}

// #region 底部弹窗相关

/** 当前显示弹窗的菜单列表 */
const currentPopupList = ref(editQuestionnairePopupList)

/** 显示底部弹窗 */
const showBottomPopup = () => {
  currentPopupList.value = editQuestionnairePopupList
  const bottomPopup: any = currentInstance?.refs.bottomPopup
  bottomPopup.open()
}


/** 点击弹窗菜单中的选项 */
const popupClickHandle = async (actionType: ActionType) => {
  switch (actionType) {
    // 删除问卷
    case 'deleteQuestionnaire':
      console.log('currentQuestionnaireCategory', currentQuestionnaireCategory.value)
      // 如果是收到的问卷，则调用的接口不同
      if (currentQuestionnaireCategory.value === 'received') {
        /** 当前问卷id */
        const questionnaireId = currentQuestionnaire.value?.id
        console.log('删除收到的问卷', questionnaireId)
        const result = await deleteReceivedQuestionnaire(questionnaireId!)
        if (result) {
          showToast('删除成功')
          navigateTo('survey')
        }
        break
      } else {
        console.log('删除问卷')
        // 向后端发送删除请求
        reqEditQuestionnaire(currentQuestionnaire.value!, true)
          .then((res) => {
            console.log('deleteQuestionnaire', res)
            // 返回问卷列表页面
            navigateTo('survey')
          })
          .catch((error) => {
            showToast('删除失败，请稍后重试')
          })
        break;
      }
  }
  const bottomPopup: any = currentInstance?.refs.bottomPopup
  bottomPopup.close()
}
// #endregion

//#region 按钮点击事件
/** 是否是从创建问卷后的「编辑标题和描述」页面进入的 */
let isFromCreateQuestionnaire = false

/** 是否是从卡片组件点击进入的 */
let isFromCard = false

// 页面挂载时，根据参数设定是否是从卡片组件点击进入的
onLoad((options: any) => {
  isFromCreateQuestionnaire = options.from === 'create-questionnaire'
  isFromCard = options.from === 'questionnaire-card'
})
/** 「设置」按钮点击事件 */
const settingBtnClickHandle = () => {
  const options = {
    from: isFromCreateQuestionnaire ? 'create-questionnaire' : isFromCard ? 'questionnaire-card' : ''
  }
  navigateTo('questionnaire-edit-title-describe', options)
}

/** 左上角返回按钮点击事件 */
const backBtnClickHandle = () => {
  navigateTo('survey')
}

// 页面卸载（系统返回）时，根据参数设定是否返回问卷列表页面
onUnload(() => {
  if (isFromCreateQuestionnaire) {
    console.log('isFromCreateQuestionnaire', isFromCreateQuestionnaire)
    navigateTo('survey')
  }
})

//#endregion

//#region 分享相关

// 分享事件回调
onShareAppMessage((res) => {
  return shareQuestionnaire(res, userInfo.name, userInfo.id)
})

/**
 * 切换分享提示对话框显示状态
 * @param isShow 是否显示
 */
const toggleShareTipDialog = (isShow: boolean) => {
  const shareTipDialog: any = currentInstance?.refs.shareTipDialog
  if (isShow) {
    shareTipDialog.open()
  } else {
    shareTipDialog.close()
  }
}

/**
 * 分享提示对话框取消按钮点击事件
 */
const shareTipDialogCancelBtnClickHandle = () => {
  toggleShareTipDialog(false)
}

/**
 * 分享提示对话框转发按钮点击事件
 */
const shareTipDialogConfirmBtnClickHandle = () => {
  toggleShareTipDialog(false)
}

//#endregion


</script>

<style lang="scss" scoped>
@import '@/static/styles/questionnaire.scss';

.page {
  // 默认模式
  // 区块间隔
  --block-gap: 8px;
  // 区块标题背景颜色
  --block-title-bg-color: #fff;
  // 问题间隔
  --question-gap: 0px;
  // 问题最小高度
  --question-min-height: 20.2564vw;
  // 问题内部padding-top
  --question-padding-top: 8px;

  // 编辑模式样式变量
  &.edit {
    --block-gap: 12px;
    --block-title-bg-color: #00000000;
    --question-gap: 8px;
    --question-min-height: 22.3077vw;
    --question-padding-top: 12px;
  }

  width: 100vw;
  height: 100vh;

  // 隐藏滚动条
  overflow: scroll;

  &::-webkit-scrollbar {
    display: none;
  }


  display: grid;
  grid-template: 'nav-bar' auto
  'container' 1fr;

  // 页面主体
  .container {
    grid-area: container;

    display: grid;
    grid-template:
      'head' auto
      'content' auto;

    position: relative;


    // 问卷头部
    .questionnaire-head {
      width: 100vw;
      background-color: #ffffff;

      padding: 16px;
      box-sizing: border-box;
      display: grid;
      grid-template:
        'cover' 37.9487vw
        '.' 16px
        'title' 8.7179vw
        '.' 8px
        'desc' auto;
      justify-items: center;

      // 头图
      .head-cover {
        grid-area: cover;
      }

      // 问卷标题
      .head-title {
        grid-area: title;
      }

      // 问卷描述
      .questionnaire-describe {
        grid-area: desc;

      }
    }

    // 问卷内容
    .content {
      grid-area: content;

      display: flex;
      flex-direction: column;
      align-items: center;

      // 身份问题区块
      .identity-block {
        margin-top: var(--block-gap);
        width: 100%;
        background-color: #fff;

        .question {
          width: 100%;
          height: 22.8205vw;

          box-sizing: border-box;
          padding: 16px;
          display: grid;
          grid-template:
            'title more' 5.3846vw
            'radio-group radio-group' 1fr
            / 1fr 4.6154vw;
          grid-row-gap: 12px;

          // 身份问题标题
          .title {
            grid-area: title;
            font-size: 3.8462vw;
          }

          .radio-group {
            grid-area: radio-group;
          }
        }
      }
    }

    // 一般问题区块
    .normal-block {
      margin-top: var(--block-gap);
      width: 100%;

      // 问题类别
      .question-type {
        padding: 16px 0 8px 16px;
        font-size: 4.6154vw;
        color: #17ce92;
        background-color: var(--block-title-bg-color);
      }

      // 问题列表
      .question-list {
        width: 100%;
        display: grid;
        grid-auto-rows: minmax(20.2564vw auto);
        grid-row-gap: var(--question-gap);

        // 问题
        .question {
          box-sizing: border-box;
          background-color: #fff;


          padding: var(--question-padding-top) 16px;
          display: grid;
          grid-template:
            'title more' auto
            'input input' minmax(8.7179vw, auto) / 1fr 46.15rpx;
          grid-row-gap: 8px;
          align-items: center;

          .question-title {
            grid-area: title;
            font-size: 28.85rpx;
            color: #ff5875;
          }

          .question-input {
            grid-area: input;

            width: calc(100% - 24px);
            background-color: #f4ebf1;
            border-radius: 2px;

            padding: 8px 12px;
            font-size: 25rpx;
          }
        }
      }
    }

    // 结束语
    .conclusion {
      margin-top: 24px;
    }
  }
}

// 分享提示对话框
.popup-dialog {
  width: 300px;
  background-color: #fff;

  border-radius: 11px;
  overflow: hidden;

  display: grid;
  grid-template:
    'title title' 50px
    'content content' 1fr
    'cancel-btn confirm-btn' 45px;

  .popup-dialog-title {
    grid-area: title;
    align-self: end;
    justify-self: center;

    color: #909399;
    font-size: 16px;
    font-weight: 500;
  }

  .popup-dialog-content {
    grid-area: content;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    padding: 20px;

    font-size: 14px;
    color: #6C6C6C;
  }

  .popup-dialog-cancel-btn {
    grid-area: cancel-btn;
    overflow: hidden;

    .button {
      background-color: #fff;
      border-radius: 0;
      scale: 1.15;
      translate: 0 3px;

      font-size: 15px;
      color: #333;
    }
  }

  .popup-dialog-confirm-btn {
    grid-area: confirm-btn;
    overflow: hidden;

    border-left-color: #f0f0f0;
    border-left-style: solid;
    border-left-width: 1px;

    .button {
      background-color: #fff;
      border-radius: 0;
      scale: 1.15;
      translate: 0 3px;

      font-size: 15px;
      color: #007aff;
    }
  }
}
</style>
